using System;
using System.IO;
using System.Web;
using System.Collections;
using System.Text;

namespace com.flajaxian
{
    /// <summary>
    /// This adapter can be used to save the files you upload in a folder located 
    /// on the same server where is located the aspx page
    /// </summary>
    public class FileSaverAdapter : FileUploaderAdapter
    {
        private string _folderName;

        public event EventHandler<FileNameDeterminingEventArgs> FileNameDetermining;

        /// <summary>
        /// Saving the file on the server. Each file triggers a separate call of this method.
        /// </summary>
        /// <param name="file">Incoming file</param>
        public override void ProcessFile(HttpPostedFile file)
        {
            if (!String.IsNullOrEmpty(this.FolderName))
            {

                string fileName = String.Concat(
                        this.Parent.Page.Server.MapPath(this.FolderName),
                        Path.DirectorySeparatorChar,
                        file.FileName
                    );

                fileName = this.OnFileNameDetermining(file, fileName);

                if (fileName != null)
                {
                    file.SaveAs(fileName);
                }
            }
        }

        protected virtual string OnFileNameDetermining(HttpPostedFile file, string fileName)
        {
            if (this.FileNameDetermining != null)
            {
                FileNameDeterminingEventArgs args = new FileNameDeterminingEventArgs(file);

                args.FileName = fileName;

                this.FileNameDetermining(this, args);

                if (args.CancelProcessing)
                {
                    return null;
                }

                return args.FileName;
            }
            return fileName;
        }

        /// <summary>
        /// The name of the folder where you would like to upload the files
        /// </summary>
        public string FolderName
        {
            get { return this._folderName; }
            set { this._folderName = value; }
        }
    }
}
